var currentUniqueId = 0;


function getUniqueId() {
    // Theoretically, this is not thread-safe...
    // ... practically, it's almost impossible that
    // two users click on a button at the same moment...
    var time = new Date();
    var ms = time.getTime();

    return numberToSortableString(ms);
}


function numberToSortableString(id) {
    // convert a number from base 10 to base 26,
    // using A-Z as digits
    var result = '';

    id = parseInt(id);

    while (id != 0) {
	var currentDigit = id % 26;
	id = Math.floor((id - currentDigit) / 26);
	result = String.fromCharCode(65 + currentDigit) + result;
    }

    // encode length of result into one char and put at the beginning
    // for example, to avoid that 'ABC' is less than 'BD'
    // -> 'CABC' is larger than 'BBD', using string comparison!
    var resultLength = String(result).length;
    var resultLengthAsChar = String.fromCharCode(64 + resultLength);
    result = resultLengthAsChar + result;

    return result;
}

function getIdSelector(id) {
    return "[id='" + id + "']";
}


function getWaveViewerId() {
    return wave.getViewer().getId();
}

/**
 * Check if the viewer is also the host, i.e. if they added the gadget to the
 * wave.
 * 
 * @return true if the viewer is the host, false otherwise.
 */
function isWaveHost() {
    var hostId = wave.getHost().getId();
    var viewerId = getWaveViewerId();
    var viewerIsWaveHost = (hostId == viewerId);
    return viewerIsWaveHost;
}


function escapeHtml(rawText) {
    // TODO: Is there a smarter way to do this?
    var textNode = document.createTextNode(rawText);
    span = document.createElement("span");
    span.appendChild(textNode);
    return span.innerHTML;
}

function trim(stringToBeTrimmed){
    if (stringToBeTrimmed == null){
        return null;
    }
    return stringToBeTrimmed.replace(/^\s+/, '').replace(/\s+$/, '');
}

